export default class Event {
  private events: Record<string, ((...args: any[]) => void)[]> = {}

  // 发布
  public dispatch(name: string, ...args: any[]) {
    if (!name) throw new Error(`[Error] arguments[0] is required string but got ${name}`)

    const events = this.events[name]

    if (!events) return false

    events.forEach(event => {
      event.apply(this, args)
    })
  }

  // 订阅
  public on(name: string, callback: (...args: any[]) => void) {
    if (!name) throw new Error(`[Error] arguments[0] is required string but got ${name}`)

    if (!callback) return

    this.events[name] = this.events[name] || []

    this.events[name].push(callback)
  }

  // 取消订阅
  public unsubscribe(name: string, callback: (...args: any[]) => void) {
    if (!name) throw new Error(`[Error] arguments[0] is required string but got ${name}`)

    if (!callback) return

    const events = this.events[name]

    if (!events || !events.length) return false

    if (!callback) {
      events.length = 0

      return null
    }

    const index = events.findIndex(event => {
      return event === callback
    })

    return events.splice(index, 1)
  }
}
